package com.oobi.showlive.cloudsql.service.auth;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oobi.showlive.cloudsql.data.conn.DBConnection;

@SuppressWarnings({"serial"})
public class ValidateUserServlet extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 resp.setContentType("text/plain");
		 PrintWriter out = resp.getWriter();
		 // Get the user's name and password
	    String name = req.getParameter("name");
	    String passwd = req.getParameter("passwd");
	    
	    if(notEmpty(name) && notEmpty(passwd)) {
	    	
	    	try {
	    		Connection conn = DBConnection.getConnection();
	        	String statement = "select username from entries where username like '" + name + "' and password like '" + passwd + "'";
	        	PreparedStatement stmt = conn.prepareStatement(statement);
	            ResultSet rs = stmt.executeQuery();
	            if(rs.next()) {
	    			out.println("Login Successful");
	    			resp.setStatus(HttpServletResponse.SC_OK);
	    			return;
	            } else {
	            	resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	            }
	    	} catch(Exception e) {
	    		resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	    	} finally {
	    		DBConnection.closeConnection();
	    	}
	    	
	    } else {
	    	resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
	    }
	}
	
	 protected boolean notEmpty(String str) {
		    if(str!=null && !"".equals(str) )
		    	return true;  
		    else 
		    	return false;
     }

}
